extends Reference


const FileUtil = preload("res://addons/function_tree/util/generate/FileUtil.gd")
const GeneratePathScript = preload("GeneratePathScript.gd")
const GenerateLayerScript = preload("GenerateLayerScript.gd")
const GenerateFunctionScript = preload("GenerateFunctionScript.gd")

const SAVE_TO_PATH = "res://addons/function_tree/global/"

var plugin : EditorPlugin
var file = File.new()
var dir = Directory.new()

var refresh_timer = Timer.new()
var gps : GeneratePathScript
var gls : GenerateLayerScript
var gfs : GenerateFunctionScript
var interval = 5.0


func get_editor_interface() -> EditorInterface:
	return plugin.get_editor_interface()


##  启动刷新脚本
## @plugin  设置所属的插件
## @interval  刷新间隔时间
## @classname  生成的类名
func start(
	plugin: EditorPlugin, 
	interval: float
) -> void:
	self.plugin = plugin
	self.interval = interval
	if not plugin.is_connected("tree_exiting", refresh_timer, "queue_free"):
		plugin.connect("tree_exiting", self, "refresh")
		plugin.connect("tree_exiting", refresh_timer, "queue_free")
	
	# 刷新计时器
	if not refresh_timer.is_inside_tree():
		refresh_timer.autostart = true
		refresh_timer.one_shot = false
		refresh_timer.wait_time = interval
		refresh_timer.connect("timeout", self, "refresh")
		plugin.add_child(refresh_timer)
	refresh_timer.start(interval)
	
	# 生成路径脚本
	gps = GeneratePathScript.new()
	gls = GenerateLayerScript.new()

	gfs = GenerateFunctionScript.new()
	gfs.add_exclude("Function")


##  刷新脚本内容
func refresh() -> void:
	var path_script = gps.generate("res://addons/function_tree/src/base/")
	save_script(path_script, "ClassDB_Path.gd")
	
	var layer_script = gls.generate("res://addons/function_tree/src/base/layer/")
	save_script(layer_script, "ClassDB_Layer.gd")
	
	var function_script = gfs.generate("res://addons/function_tree/src/base/function/")
	save_script(function_script, "ClassDB_Function.gd")


##  保存脚本 
## @script  脚本
## @path  保存到的路径
func save_script(script: GDScript, name: String):
	var path = SAVE_TO_PATH.plus_file(name)
	# 脚本内容不相同，则进行修改
	if script && not FileUtil.equals_file_content(path, script.source_code):
		FileUtil.save(path, script)
		update_filesystem()


##  更新文件系统，让类被扫描生效
## 在这里会防止一帧内多次调用，所以设置 0.1 秒间隔时间
var __update := false
func update_filesystem():
	if __update == false:
		__update = true
		get_editor_interface().get_script_editor().notification(Node.NOTIFICATION_WM_FOCUS_OUT)
		yield(get_editor_interface().get_tree().create_timer(0.1), "timeout")
#		var fs = get_editor_interface().get_resource_filesystem()
#		fs.scan()
#		fs.update_script_classes()
#		get_editor_interface() \
#			.get_script_editor() \
#			.notification(Node.NOTIFICATION_WM_FOCUS_IN)
		#刷新文件系统
		get_editor_interface().get_resource_filesystem().scan()
		#刷新脚本编辑器脚本
		get_editor_interface().get_script_editor().notification(Node.NOTIFICATION_WM_FOCUS_IN)
		
		__update = false
		
		print('--refresh')


